package com.example.gbasedemo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlProcessor {

    public static void main(String[] args) {
        String sql = "SELECT * FROM \"table_name\" WHERE " +
                "column1 = 'It''s \"sunny\"' AND \"column2\" = 'Another ''example'''";

        // 正则表达式匹配双引号包围的内容
        Pattern pattern = Pattern.compile("\"([^\"]*)\"");
        Matcher matcher = pattern.matcher(sql);

        StringBuffer result = new StringBuffer();
        int lastEnd = 0;

        while (matcher.find()) {
            String matchedStr = matcher.group(0).trim();
            // 检查匹配项之前的部分是否包含未闭合的单引号
            boolean isInSingleQuotes = isWithinSingleQuotes(sql.substring(0, matcher.start()));

            // 如果当前匹配不在单引号内部，则替换掉双引号及其内容
            if (!isInSingleQuotes) {
                result.append(sql, lastEnd, matcher.start()); // 添加从上次结束到本次开始前的部分
                matchedStr = matchedStr.substring(1,matchedStr.length()-1);
                result.append(matchedStr);
                // 不添加被替换的双引号部分，即相当于替换成空串
            } else {
                // 否则，保留原样
                result.append(sql, lastEnd, matcher.end());
            }
            lastEnd = matcher.end();
        }

        // 添加最后的部分
        result.append(sql.substring(lastEnd));
        System.out.println("origin SQL: " + sql);
        System.out.println("Processed SQL: " + result.toString());
    }


    /**
     * 判断从开始到指定位置之前的部分是否包含未闭合的单引号，考虑转义情况。
     */
    private static boolean isWithinSingleQuotes2(String str) {
        boolean inSingleQuote = false;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '\\') {
                // 如果当前字符是反斜杠，则跳过下一个字符（无论是什么）
                i++;
            } else if (c == '\'') {
                // 翻转inSingleQuote的状态
                inSingleQuote = !inSingleQuote;
            }
        }
        return inSingleQuote;
    }

    private static boolean isWithinSingleQuotes(String str) {
        boolean inSingleQuote = false;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '\\') {
                // 如果当前字符是反斜杠，则跳过下一个字符（无论是什么）
                i++;
            } else if (c == '\'') {
                if (i + 1 < str.length() && str.charAt(i + 1) == '\'') {
                    // 遇到了两个连续的单引号，表示字符串内容中的单引号
                    i++; // 跳过下一个单引号
                } else {
                    // 单个单引号，切换isInSingleQuotes状态
                    inSingleQuote = !inSingleQuote;
                }
            }
        }
        return inSingleQuote;
    }
}
